package com.jay.media.music.ui.music

import android.media.browse.MediaBrowser
import android.view.LayoutInflater
import android.view.RoundedCorner
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.jay.media.kit.LogHelper
import com.jay.media.music.ui.MediaApplication
import com.jay.media.music.ui.R

/**
 * Create by xuzhou4
 * Date 2021/11/12
 */
class MediaAdapter(var list: List<MediaBrowser.MediaItem>? = null) :
    RecyclerView.Adapter<MediaAdapter.Holder>() {

    val TAG = LogHelper.makeLogTag(this::class.java)

    var mOnItemClickListener: OnItemClickListener? = null

    class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var iconMusic: ImageView = itemView.findViewById(R.id.icon_music)
        var titleTextView: TextView = itemView.findViewById(R.id.title_textview)
        var subTitleTextView: TextView = itemView.findViewById(R.id.subtitle_textview)
        var musicMenuButton: ImageView = itemView.findViewById(R.id.music_menu_button)
    }

    interface OnItemClickListener {
        fun onItemClick(view: View, item: MediaBrowser.MediaItem)
        fun onItemMenuClick(view: View, position: Int, item: MediaBrowser.MediaItem)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_song_layout, null)
        return Holder(itemView)
    }

    override fun onBindViewHolder(holder: Holder, position: Int) {
        val item = list?.get(position)
        item?.also {
            Glide.with(MediaApplication.getContext()).load(item.description.iconUri?.toString())
                .error(R.drawable.ic_music_small)
                .apply(RequestOptions.bitmapTransform(RoundedCorners(20))).into(holder.iconMusic)
            holder.titleTextView.text = item.description.title
            holder.subTitleTextView.text = item.description.subtitle
            holder.musicMenuButton.visibility = if (item.isPlayable) View.VISIBLE else View.GONE
        }
        holder.itemView.setOnClickListener {
            if (mOnItemClickListener != null && item != null) {
                LogHelper.d(TAG, "onItemClick $item")
                mOnItemClickListener?.onItemClick(it, item)
            }
        }

        holder.musicMenuButton.setOnClickListener {
            if (mOnItemClickListener != null && item != null) {
                mOnItemClickListener?.onItemMenuClick(it, position, item)
            }
        }
    }

    override fun getItemCount(): Int {
        return list?.size ?: 0
    }
}